package com.kuaidian.util;

import java.io.IOException;

import org.apache.log4j.Logger;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;

public class JPushUtil {
	private static Logger LOG = Logger.getLogger(JPushUtil.class);
	
	public static void  pushTransmissionMsg(String clientId,String clientType,String msgStr) throws IOException{
		JPushInfo info = getJPushInfo(clientType);
	    JPushClient jpushClient = new JPushClient(info.MasterSecret, info.AppKey, 3);

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_cid(clientId,msgStr);

        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            LOG.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            LOG.error("Should review the error, and fix the request", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
	}

    public static PushPayload buildPushObject_cid(String cid,String msg) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.registrationId(cid))
                 .setMessage(Message.content(msg))
                 .build();
    }
	

	public static JPushInfo  getJPushInfo(String clientType){
		JPushInfo appInfo = new JPushInfo();
		
		if (clientType.equals("1")) {
			appInfo.AppKey =       "8763cf89da970a00b52feccf";
			appInfo.MasterSecret = "50b29f0726e7b08d15d8c1b4";
		}else{
			appInfo.AppKey =       "16380a655619a7c9523d2282";
			appInfo.MasterSecret = "a6748c705d9a5d2677112a67";
		}
		return appInfo;
	}
	public static  class JPushInfo{

		public  String AppKey;
		public  String MasterSecret;
		
	}
	
	
	
}
